#include "thread_pool.h"
//主线程调用:处理客户端发过来的消息
void handleMessage(int sockfd, int epfd, task_queue_t * que)
{
    //消息格式：cmd content
    //1.1 获取消息长度
    int length = -1;
    int ret = recvn(sockfd, &length, sizeof(length));
    printf("recv length: %d\n", length);

    //1.2 获取消息类型
    int cmdType = -1;
    ret = recvn(sockfd, &cmdType, sizeof(cmdType));
    printf("recv cmd type: %d\n", cmdType);
    task_t *ptask = (task_t*)calloc(1, sizeof(task_t));
    ptask->peerfd = sockfd;
    ptask->type= cmdType;
    if(length > 0) {
        //1.3 获取消息内容
        ret = recvn(sockfd, ptask->data, length);
        if(ret > 0) {
            //往线程池中添加任务
            taskEnque(que, ptask);
        }
    } else if(length == 0){
        taskEnque(que, ptask);
    }

    if(ret == 0) {//连接断开的情况
        printf("\nconn %d is closed.\n", sockfd);
        delEpollReadfd(epfd, sockfd);
        close(sockfd);
    }
}

void doTask(task_t * task)
{
    assert(task);
    switch(task->type) {
    case CMD_TYPE_PWD:  
        pwdCommand(task);   break;
    case CMD_TYPE_CD:
        cdCommand(task);    break;
    case CMD_TYPE_LS:
        lsCommand(task);    break;
    case CMD_TYPE_MKDIR:
        mkdirCommand(task);  break;
    case CMD_TYPE_RMDIR:
        rmdirCommand(task);  break;
    case CMD_TYPE_RM:
        rmCommand(task);  break;
    case CMD_TYPE_GETS:
        getsCommand(task);  break;
    case CMD_TYPE_PUTS:
        putsCommand(task);  break;
    case CMD_TYPE_QUIT:
        quitCommand(task);  break;
    case CMD_TYPE_NOTCMD:
        notCommand(task);   break;
    }
}

void pwdCommand(task_t * task){
    //查看命令是否正确 
    if(task==NULL || task->type!=CMD_TYPE_PWD){
        printf("Yours Command error!\n");
        exit(1);
    }
    //检验传过来的数据 如果是pwd后还有字符，则报错
    if(strcmp("",task->data)!=0){
        printf("Yours Paraments error\n");
    }

  char buf[128]={0};
  char *p = getcwd(NULL, 0);
  if (!p) {
    fprintf(stderr, "Failed to pwd: %s\n", strerror(errno));
    exit(1);
  }

  strcpy(buf,p);
  printf("%s\n",buf);
}

void cdCommand(task_t * task)
{
    //是否为有效路径
      if (task == NULL || task->type != CMD_TYPE_CD) {
          printf("Invalid task or command type for cdCommand.\n");
          return;
      }
      char buf[128]={'0'};
      char *home_dir = getenv("HOME");
      // 检查data字段是否为空 
      if (task->data[0] != '\0') {	  
          
	  getcwd(buf,sizeof(buf));
	  printf("current path:%s\n",buf);
	  chdir(task->data);

	  memset(buf,0 ,sizeof(buf));
	  getcwd(buf,sizeof(buf));
	  printf("current path:%s\n",buf);
          
	  printf("execute cd command to: %s\n", task->data);
      } else {
	  getcwd(buf,sizeof(buf));
	  printf("current path:%s\n",buf);
	      chdir(home_dir);
	  getcwd(buf,sizeof(buf));
	  printf("current path:%s\n",buf);
      }
}
int Is_directory(const char *path) {
    struct stat st;
    if (stat(path, &st) == 0) {
        return S_ISDIR(st.st_mode);
    }
    return 0; // 返回0表示不是目录，或者stat调用失败
}

void lsCommand(task_t * task)
{
	 DIR *dir;
    struct dirent *entry;
    char buf[128];
    memset(buf,0,sizeof(buf));

    //是否为空
    if(strcmp("\0",task->data)==0){
        getcwd(buf,sizeof(buf));
	strcpy(task->data,buf);
    }
    //是否为一个路径,返回0表示错误
    int ret=Is_directory(task->data);
	    if(ret==0){
	      printf("is not a directory\n");
	      exit(1);
    }

    if ((dir = opendir(task->data)) == NULL) {
        perror("opendir");
        exit(EXIT_FAILURE);
    }


    while ((entry = readdir(dir)) != NULL) {
      if(strcmp(".",entry->d_name)==0||
         strcmp("..",entry->d_name)==0 )
                  continue ;
        printf("%s\n", entry->d_name);
    }

    closedir(dir);

}

void mkdirCommand(task_t * task)
{
    printf("execute mkdir command.\n");
}

void rmdirCommand(task_t * task)
{
    printf("execute rmdir command.\n");
}

void rmCommand(task_t * task)
{
    printf("execute rm command.\n");
}

void getsCommand(task_t * task)
{
    printf("execute gets command.\n");
    int sockfd = task->peerfd;
    transferFile(sockfd, task->data);
    //重新监听
    addEpollReadfd(task->epfd, task->peerfd);
}

void putsCommand(task_t * task)
{
    printf("execute puts command.\n");
}

void quitCommand(task_t * task)
{
    printf("execute quit command.\n");
}

void notCommand(task_t * task)
{
    printf("execute not command.\n");
}
